package com.ruoyi.common.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.model.bo.TokenBo;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class TokenUtils {

    // 有效期
    public static final Long JWT_TTL = 2592000000L;

    // JWT令牌信息
    public static final String JWT_KEY = "nB4A7QEJJSzWMfa1aOOPs4gNnhKFYCMC";

    /**
     * 颁发token
     * @param userId
     * @param openid
     * @return
     */
    public static String genrateToken(int userId, String openid) {
        TokenBo tokenBo = new TokenBo();
        tokenBo.setUserId(userId);
        tokenBo.setOpenid(openid);
        tokenBo.setAdmin("1");
        String tokenJson = JsonUtil.toJSONString(tokenBo);
        if (StrUtil.isBlank(tokenJson)) {
            throw new ServiceException("颁发token失败");
        }
        return createJWT(tokenJson);
    }

    public static String createJWT(String subject) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        long expMillis = nowMillis + JWT_TTL;  //过期时间
        Date expDate = new Date(expMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(String.valueOf(UUID.randomUUID()))                      // 设置唯一编号
                .setSubject(subject)            // 设置主题 可以是JSON数据
                .setIssuer("kangfu")
                .setIssuedAt(now)               // 设置签发日期
                .setExpiration(expDate)         // 设置过期时间
                .signWith( SignatureAlgorithm.HS256, secretKey); //设置签名 使用HS256算法 并设置SecretKey(字符串)
        return builder.compact();
    }

    /**
     * 生成加密secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getEncoder().encode(JWT_KEY.getBytes());
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "HmacSHA256");
        return key;
    }

}
